<?php
/**
 * User: 苏翔
 * Date: 2024/8/11 19:01
 */

namespace App\Service;

use App\Amqp\Producers\FundBalanceProducer;
use App\Dao\FundCacheDao;
use App\Dao\FundConfDao;
use App\Dao\HscoinConfDao;
use App\Dao\HscoinStatsDao;
use App\HscoinConf;
use Hyperf\Amqp\Producer;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;

class HscoinStatsService extends BaseService
{
    #[Inject]
    protected HscoinConfDao $confDao;
    #[Inject]
    private HscoinStatsDao $dao;
    #[Inject]
    private Redis $redis;

    #[Inject]
    private Producer $producer;

    public function __construct()
    {
    }

    /**
     * use cache
     * @return float
     */
    function getBalance(): float
    {
        $rs = (float)$this->dao->getBalance();
        return round($rs, 2);
    }

    function getCache()
    {
        $rs = $this->redis->get(HscoinConf::STATS_CACHE_KEY);
        if (!$rs) {
            return $this->setCache();
        }
        $rt = $rs ? json_decode($rs, true) : [];
        return [(array)$rt, 0, '读取从缓存读取数据'];
        //return $this->model->get()->toArray();
    }

    function setCache()
    {
        $rs = $this->dao->all()->toArray();

        if ($this->redis->setex(HscoinConf::STATS_CACHE_KEY, HscoinConf::STATS_CACHE_LIFE_TIME, $rs)) {
            return [$rs, 0];
        }
        return [$rs, 1];
    }

    function mqBalance()
    {
        $balance = $this->getBalance();
        dev_log('balance:',$balance);
        return $this->producer->produce(new FundBalanceProducer($balance), true, 5);
    }

    function updateBaseAmount($amount)
    {
        $data = [
            'cache_type'=>HscoinConf::STATS_TYPE_BASE_BALANCE,
            'cnt'=>$amount,
            ];
        $rs = $this->dao->where('cache_type',HscoinConf::STATS_TYPE_BASE_BALANCE)->value('id');
        if ($rs) {
            $this->dao->where('id',$rs)->update($data);
        } else {
            $this->dao->create($data);
        }
    }

    function getStats()
    {
        return    $this->dao->all()->toArray();
    }
}